/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Connection;


import enteties.User;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.DatatypeConverter;

/**
 *
 * @author Trung Kien
 */
public class UserDB {
    private String url;
    private String user;
    private String dbpassword;

    public UserDB(String url, String user, String password) {
        this.url = url;
        this.user = user;
        this.dbpassword = password;
    }
    private String hashPassword(String password){
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            byte[] output = md.digest(password.getBytes());
            return DatatypeConverter.printHexBinary(output);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(ConnectionDB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
}
    public User login(String username, String password){
        try {
            Connection conn = ConnectionUtil.getConnection(url, user, dbpassword);
            CallableStatement cstmt = conn.prepareCall("{call dangnhap(?,?)}");
            
            cstmt.setString("username", username);
            cstmt.setString("password",hashPassword(password));
            ResultSet rs = cstmt.executeQuery();
            if(rs.next()){
                int userid = rs.getInt("userid");
                User u = new User(userid, username, password);
                return u;
            }
        } catch (Exception e) {
        }
        return null;
    }
}
